package com.party.refund.jms.listener;

import com.party.common.constant.Constant;
import com.party.core.service.crowdfund.ISupportService;
import com.party.refund.biz.SupportBizService;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: huangzequn
 * @Date: 2019/5/16 15:58
 */
@Component(value = "supportRefundListenerWeb")
public class SupportRefundListener implements javax.jms.MessageListener {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ISupportService supportService;

    private ExecutorService threadPool = Executors.newFixedThreadPool(10);

    @Autowired
    private SupportBizService supportBizService;

    public void onMessage(Message message) {
        try {
            if (message instanceof ActiveMQMessage) {
                ActiveMQMapMessage mqMessage = (ActiveMQMapMessage) message;
                String id = mqMessage.getString(Constant.TYPE_KEY);
                String isTwiceRefund = mqMessage.getString("isTwiceRefund");
                if ("YES".equals(isTwiceRefund)) {
                    //如果重试了之后还是退款失败，在次入队列，出队列的时候单线程执行
                    logger.info("在次入队列的支持者出队列了，单线程出队列,支持者id为：" + id);
                    supportBizService.refund(id);

                } else {
                    threadPool.execute(() -> supportBizService.refund(id));
                }
            }
        } catch (JMSException e) {
            logger.error("退款消息队列异常", e);
        }
    }
}

